#!/usr/bin/env python3
"""
Dockerfile 语法验证器
检查Dockerfile的基本语法和多架构支持
"""

import re
import sys

def validate_dockerfile(file_path):
    """验证Dockerfile语法"""
    errors = []
    warnings = []
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            lines = content.split('\n')
    except FileNotFoundError:
        return [f"文件不存在: {file_path}"], []
    
    # 检查多架构支持
    has_platform = '--platform=' in content
    has_build_args = bool(re.search(r'ARG TARGET(OS|ARCH|PLATFORM)', content))
    has_multiarch_from = bool(re.search(r'FROM --platform=\$BUILDPLATFORM', content))
    
    # 检查基本语法
    for i, line in enumerate(lines, 1):
        line = line.strip()
        if not line or line.startswith('#'):
            continue
            
        # 检查FROM语句
        if line.startswith('FROM'):
            if not has_platform and 'multiarch' in file_path.lower():
                warnings.append(f"第{i}行: 建议添加 --platform 参数以支持多架构")
        
        # 检查RUN语句
        if line.startswith('RUN'):
            if 'apt-get' in line and '-y' not in line:
                warnings.append(f"第{i}行: apt-get 建议使用 -y 参数")
            if 'apk' in line and '--no-cache' not in line:
                warnings.append(f"第{i}行: apk 建议使用 --no-cache 参数")
        
        # 检查COPY语句
        if line.startswith('COPY'):
            if not line.endswith('.'):
                parts = line.split()
                if len(parts) < 3:
                    errors.append(f"第{i}行: COPY 语句格式错误")
    
    # 检查多架构相关配置
    if 'multiarch' in file_path.lower():
        if not has_build_args:
            errors.append("缺少多架构构建参数 (TARGETOS, TARGETARCH, TARGETPLATFORM)")
        if not has_multiarch_from:
            errors.append("建议使用 --platform=$BUILDPLATFORM 优化构建性能")
    
    return errors, warnings

def main():
    """主函数"""
    dockerfiles = [
        "Dockerfile",
        "Dockerfile.multiarch"
    ]
    
    print("🔍 Dockerfile 语法验证")
    print("=" * 50)
    
    all_errors = 0
    all_warnings = 0
    
    for dockerfile in dockerfiles:
        print(f"\n📋 检查文件: {dockerfile}")
        print("-" * 30)
        
        errors, warnings = validate_dockerfile(dockerfile)
        
        if errors:
            print("❌ 错误:")
            for error in errors:
                print(f"   - {error}")
            all_errors += len(errors)
        
        if warnings:
            print("⚠️  警告:")
            for warning in warnings:
                print(f"   - {warning}")
            all_warnings += len(warnings)
        
        if not errors and not warnings:
            print("✅ 语法检查通过")
    
    print("\n" + "=" * 50)
    print(f"📊 检查结果: {all_errors} 个错误, {all_warnings} 个警告")
    
    if all_errors == 0:
        print("✅ 所有 Dockerfile 语法验证通过")
        return 0
    else:
        print("❌ 存在语法错误，请修复后重试")
        return 1

if __name__ == "__main__":
    sys.exit(main())